<template>
  <el-upload class="avatar-uploader" action="#" :show-file-list="false" :on-success="handleAvatarSuccess"
    :before-upload="beforeAvatarUpload" :http-request="props?.request" :name="props?.postImage" @exceed="handleExceed"
    @error="handleError">
    <img v-if="imageUrl" :src="imageUrl" class="avatar" />
    <el-icon v-else class="avatar-uploader-icon">
      <Plus />
    </el-icon>
  </el-upload>
</template>

<script lang="ts" setup>
import { ref } from "vue";
import { ElMessage } from "element-plus";
import { Plus } from "@element-plus/icons-vue";

import type { UploadProps } from "element-plus";

const props = defineProps<{
  request: (params: any) => void;
  postImage?: string; // treeFilter 标题 ==> 非必传
}>();

const imageUrl = defineModel<string>({ default: "" });

const handleAvatarSuccess: UploadProps["onSuccess"] = (response, uploadFile) => {
  if (response) {
    imageUrl.value = response.image_url;
  }

};









const beforeAvatarUpload: UploadProps['beforeUpload'] = async (rawFile) => {




  let result = false;

  await new Promise((resolve, reject) => {
    var reader = new FileReader();
    reader.onload = function (event) {
      if (rawFile.type !== 'image/png' && rawFile.type !== 'image/jpg' && rawFile.type !== 'image/jpeg') {
          ElMessage.error('图片仅支持jpg、jpeg、png格式!')
          return reject(false);
        } 

        if (rawFile.size / 1024 >100) {
          ElMessage.error('图片大小不能超过100kb!')
          return reject(false);
        }

      var txt = event.target.result;
      var img = document.createElement("img");
      img.src = txt;
     img.onload = function () {
        if (img.width > 100 || img.height > 100) {
          ElMessage.error('图片尺寸最大为100*100')
          return reject(false);
        }
        resolve(true)
      }
    };
    reader.readAsDataURL(rawFile);

  }).then(res => {
    result = true

  }).catch(er => {

    result = false
  })
  return result


}






























const handleExceed: UploadInstance["onExceed"] = (files, uploadFiles) => {
  const limit = props.limit;
  if (!limit) return;
  if (files.length + uploadFiles.length > limit) {
    ElMessage.warning(`${proxy?.$t("staff_list.upload_limit_message")} ${limit - uploadFiles.length}`);
  }
};

const handleError: UploadInstance["onError"] = error => {
  ElMessage.error(error.message);
};
</script>

<style scoped>
.avatar-uploader .avatar {
  width: 60px;
  height: 60px;
  display: block;
}
</style>

<style>
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 60px;
  height: 60px;
  text-align: center;
}
</style>
